package com.vviton.zyhj.common.utils.idgen;

import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 单机有序的序号生成器 
 */
public class StandaloneIdMake implements IdMake {

	private static final Log LOG = LogFactory.getLog(StandaloneIdMake.class);

	private Random random = new Random();
	private long sequence = 0L;
	// 开始时间，从2016开始
	private long twepoch = 1451577600000L;
	// 毫秒内自增位
	private long sequenceBits = 22L;
  // 毫秒内最大值
	private long sequenceMask = -1L ^ (-1L << sequenceBits);
	//时间毫秒左移22位
	private long timestampLeftShift = sequenceBits;
	private long lastTimestamp = -1L;

	public StandaloneIdMake() {
	}
  
	// 保证有序
	public synchronized long nextId() {
		
		long timestamp = timeGen();
	  // 时间校验
		if (timestamp < lastTimestamp) {
			LOG.error(String.format(
			    "clock is moving backwards.  Rejecting requests until %d.",
			    lastTimestamp));
			throw new RuntimeException(
			    String
			        .format(
			            "Clock moved backwards.  Refusing to generate id for %d milliseconds",
			            lastTimestamp - timestamp));
		}
    
		if (lastTimestamp == timestamp) {
			sequence = (sequence + 1) & sequenceMask;
			if (sequence == 0) {
				timestamp = tilNextMillis(lastTimestamp);
			}
		} else {
			// 随机0-9
			sequence = random.nextInt(10);//0L;
		}

		lastTimestamp = timestamp;

		return ((timestamp - twepoch) << timestampLeftShift) | sequence;
	}

	// 等待下一个毫秒的到来 
	protected long tilNextMillis(long lastTimestamp) {
		long timestamp = timeGen();
		while (timestamp <= lastTimestamp) {
			timestamp = timeGen();
		}
		return timestamp;
	}
  // 当前时间
	protected long timeGen() {
		return System.currentTimeMillis();
	}

}
